#ifndef ADMINUSERMANAGE_H
#define ADMINUSERMANAGE_H

#include <QWidget>
#include <QTableView>
#include <QHeaderView>
#include <QDateTime>
#include "sqlitemanage.h"
QT_BEGIN_NAMESPACE
namespace Ui { class AdminUserManage; }
QT_END_NAMESPACE

class UserModel : public QSqlRelationalTableModel {
public:
    explicit UserModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
        : QSqlRelationalTableModel(parent, db) {
        setTable("users");
        setEditStrategy(QSqlTableModel::OnManualSubmit); // 手动提交修改
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override {
        // 密码字段自动加密
        if (index.column() == 2 && !value.toString().isEmpty()) {
            QString encrypted = QCryptographicHash::hash(value.toString().toUtf8(),
                                     QCryptographicHash::Sha256).toHex();
            return QSqlRelationalTableModel::setData(index, encrypted, role);
        }
        // 唯一性验证
        if (index.column() == 1 || index.column() == 3 || index.column() == 4) {
            QSqlQuery query;
            query.prepare(QString("SELECT COUNT(*) FROM users WHERE %1=?").arg(headerData(index.column(), Qt::Horizontal).toString()));
            query.addBindValue(value);
            if (query.exec() && query.next() && query.value(0).toInt() > 0) {
                QMessageBox::warning(nullptr, tr("错误"), tr("该值已存在！"));
                return false;
            }
        }
        return QSqlRelationalTableModel::setData(index, value, role);
    }
};

class AdminUserManage : public QWidget
{
    Q_OBJECT

public:
    AdminUserManage(QWidget *parent = nullptr);
    ~AdminUserManage();
    void setWidgetInfo(QString);
    void getUserInfo(QString);

private:
    Ui::AdminUserManage *ui;
    SqliteManage *m_pSqliteManage;
    UserModel *model;

    QString user_role;
    QString UserName;
    QString PassWord;
    QString email;
    QString phone;
    QString nickname;

    void setupUI();
    void loadData();
    void addUser();
    void deleteUser();
    void saveChanges();
};
#endif // ADMINUSERMANAGE_H
